import { MockMethod } from 'vite-plugin-mock';
const mockUsers = [
  {
    password: '123123',
    username: '123',
  },
];
export default [
  {
    url: '/api/login',
    method: 'post',
    response: ({ body }) => {
      console.log(1111)
      console.log('Mock /api/login called with body:', body); // 调试日志
      const { username, password } = body;
      const user = mockUsers.find(
        (user) => user.username === username && user.password === password
      );
      if (user) {
        return {
          code: 200,
          message: '登录成功',
          data: {
            token: `mock-token-${Math.random().toString(36).slice(2)}`,
            user: {
              username: user.username,
            },
          },
        };
      } else {
        return {
          code: 401,
          message: '邮箱或密码错误',
          data: null,
        };
      }
    },
  },
  // GET 请求
  {
    url: '/api/registry',
    method: 'post',
    response: ({ body }) => {
      const {username,password} = body;
      const existFlag = mockUsers.find(user=> user.username == username);
      mockUsers.push(body)
      return existFlag ? {code:402,message:'当前用户已存在'} : {code:200,message:'注册成功'}
    },
  },
  // POST 请求
  {
    url: '/api/post',
    method: 'post',
    timeout: 2000, // 模拟延迟
    response: ({ body }) => {
      return {
        code: 0,
        data: {
          name: 'vben',
          postData: body,
        },
      };
    },
  },
  // 自定义响应
  {
    url: '/api/text',
    method: 'post',
    rawResponse: async (req, res) => {
      let reqBody = '';
      await new Promise((resolve) => {
        req.on('data', (chunk) => {
          reqBody += chunk;
        });
        req.on('end', () => resolve(undefined));
      });
      res.setHeader('Content-Type', 'text/plain');
      res.statusCode = 200;
      res.end(`hello, ${reqBody}`);
    },
  },
] as MockMethod[];